{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4YErqpfH9jVI"
   },
   "source": [
    "# RAG Evaluation\n",
    "_Authored by: [Aymeric Roucher](https://huggingface.co/m-ric)_\n",
    "\n",
    "This notebook demonstrates how you can evaluate your RAG (Retrieval Augmented Generation), by building a synthetic evaluation dataset and using LLM-as-a-judge to compute the accuracy of your system.\n",
    "\n",
    "For an introduction to RAG, you can check [this other cookbook](rag_zephyr_langchain)!\n",
    "\n",
    "RAG systems are complex: here a RAG diagram, where we noted in blue all possibilities for system enhancement:\n",
    "\n",
    "<img src=\"https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/RAG_workflow.png\" height=\"700\">\n",
    "\n",
    "Implementing any of these improvements can bring a huge performance boost; but changing anything is useless if you cannot monitor the impact of your changes on the system's performance!\n",
    "So let's see how to evaluate our RAG system.\n",
    "\n",
    "### Evaluating RAG performance\n",
    "\n",
    "Since there are so many moving parts to tune with a big impact on performance, benchmarking the RAG system is crucial.\n",
    "\n",
    "For our evaluation pipeline, we will need:\n",
    "1. An evaluation dataset with question - answer couples (QA couples)\n",
    "2. An evaluator to compute the accuracy of our system on the above evaluation dataset.\n",
    "\n",
    "➡️ It turns out, we can use LLMs to help us all along the way!\n",
    "1. The evaluation dataset will be synthetically generated by an LLM 🤖, and questions will be filtered out by other LLMs 🤖\n",
    "2. An [LLM-as-a-judge](https://huggingface.co/papers/2306.05685) agent 🤖 will then perform the evaluation on this synthetic dataset.\n",
    "\n",
    "__Let's dig into it and start building our evaluation pipeline!__ First, we install the required model dependancies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "bCKBvOcp9jVK"
   },
   "outputs": [],
   "source": [
    "!pip install -q torch transformers langchain sentence-transformers tqdm openpyxl openai pandas datasets langchain-community ragatouille"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "k_lJFbYm9jVL"
   },
   "outputs": [],
   "source": [
    "%reload_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "oIlNZ1Mn9jVL"
   },
   "outputs": [],
   "source": [
    "from tqdm.auto import tqdm\n",
    "import pandas as pd\n",
    "from typing import Optional, List, Tuple\n",
    "import json\n",
    "import datasets\n",
    "\n",
    "pd.set_option(\"display.max_colwidth\", None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import notebook_login\n",
    "\n",
    "notebook_login()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "zeW8P62J9jVM"
   },
   "source": [
    "### Load your knowledge base"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "YRbm5tNF9jVM"
   },
   "outputs": [],
   "source": [
    "ds = datasets.load_dataset(\"m-ric/huggingface_doc\", split=\"train\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "wy9CKj0M9jVM"
   },
   "source": [
    "# 1. Build a synthetic dataset for evaluation\n",
    "We first build a synthetic dataset of questions and associated contexts. The method is to get elements from our knowledge base, and ask an LLM to generate questions based on these documents.\n",
    "\n",
    "Then we setup other LLM agents to act as quality filters for the generated QA couples: each of them will act as the filter for a specific flaw."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QkoEgiDg9jVM"
   },
   "source": [
    "### 1.1. Prepare source documents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "3gTOlRKO9jVM"
   },
   "outputs": [],
   "source": [
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain.docstore.document import Document as LangchainDocument\n",
    "\n",
    "langchain_docs = [\n",
    "    LangchainDocument(page_content=doc[\"text\"], metadata={\"source\": doc[\"source\"]})\n",
    "    for doc in tqdm(ds)\n",
    "]\n",
    "\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter(\n",
    "    chunk_size=2000,\n",
    "    chunk_overlap=200,\n",
    "    add_start_index=True,\n",
    "    separators=[\"\\n\\n\", \"\\n\", \".\", \" \", \"\"],\n",
    ")\n",
    "\n",
    "docs_processed = []\n",
    "for doc in langchain_docs:\n",
    "    docs_processed += text_splitter.split_documents([doc])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WjrNhcCh9jVN"
   },
   "source": [
    "### 1.2. Setup agents for question generation\n",
    "\n",
    "We use [Mixtral](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) for QA couple generation because it it has excellent performance in leaderboards such as [Chatbot Arena](https://huggingface.co/spaces/lmsys/chatbot-arena-leaderboard)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {
    "id": "GoRySj3Q9jVN"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'This is a test context for the `@mui/material` library.\\n\\n## Installation\\n\\n```sh\\nnpm install @mui/material\\n```\\n\\n## Usage\\n\\n```jsx\\nimport React from \\'react\\';\\nimport { Button } from \\'@mui/material\\';\\n\\nfunction App() {\\n  return (\\n    <div className=\"App\">\\n      <Button variant=\"contained\" color=\"primary\">\\n        Hello World\\n      </Button>\\n    </div>\\n  );\\n}\\n\\nexport default App;\\n```\\n\\n## Documentation\\n\\n- [Material-UI](https://material-ui.com/)\\n- [Material Design](https://material.io/)'"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from huggingface_hub import InferenceClient\n",
    "\n",
    "\n",
    "repo_id = \"mistralai/Mixtral-8x7B-Instruct-v0.1\"\n",
    "\n",
    "llm_client = InferenceClient(\n",
    "    model=repo_id,\n",
    "    timeout=120,\n",
    ")\n",
    "\n",
    "\n",
    "def call_llm(inference_client: InferenceClient, prompt: str):\n",
    "    response = inference_client.post(\n",
    "        json={\n",
    "            \"inputs\": prompt,\n",
    "            \"parameters\": {\"max_new_tokens\": 1000},\n",
    "            \"task\": \"text-generation\",\n",
    "        },\n",
    "    )\n",
    "    return json.loads(response.decode())[0][\"generated_text\"]\n",
    "\n",
    "\n",
    "call_llm(llm_client, \"This is a test context\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {
    "id": "hIM_DJRo9jVN"
   },
   "outputs": [],
   "source": [
    "QA_generation_prompt = \"\"\"\n",
    "Your task is to write a factoid question and an answer given a context.\n",
    "Your factoid question should be answerable with a specific, concise piece of factual information from the context.\n",
    "Your factoid question should be formulated in the same style as questions users could ask in a search engine.\n",
    "This means that your factoid question MUST NOT mention something like \"according to the passage\" or \"context\".\n",
    "\n",
    "Provide your answer as follows:\n",
    "\n",
    "Output:::\n",
    "Factoid question: (your factoid question)\n",
    "Answer: (your answer to the factoid question)\n",
    "\n",
    "Now here is the context.\n",
    "\n",
    "Context: {context}\\n\n",
    "Output:::\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lVFc-lVy9jVN"
   },
   "source": [
    "Now let's generate our QA couples.\n",
    "For this example, we generate only 10 QA couples and will load the rest from the Hub.\n",
    "\n",
    "But for your specific knowledge base, given that you want to get at least ~100 test samples, and accounting for the fact that we will filter out around half of these with our critique agents later on, you should generate much more, in the >200 samples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8fteqDDD9jVN"
   },
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "N_GENERATIONS = 10  # We intentionally generate only 10 QA couples here for cost and time considerations\n",
    "\n",
    "print(f\"Generating {N_GENERATIONS} QA couples...\")\n",
    "\n",
    "outputs = []\n",
    "for sampled_context in tqdm(random.sample(docs_processed, N_GENERATIONS)):\n",
    "    # Generate QA couple\n",
    "    output_QA_couple = call_llm(\n",
    "        llm_client, QA_generation_prompt.format(context=sampled_context.page_content)\n",
    "    )\n",
    "    try:\n",
    "        question = output_QA_couple.split(\"Factoid question: \")[-1].split(\"Answer: \")[0]\n",
    "        answer = output_QA_couple.split(\"Answer: \")[-1]\n",
    "        assert len(answer) < 300, \"Answer is too long\"\n",
    "        outputs.append(\n",
    "            {\n",
    "                \"context\": sampled_context.page_content,\n",
    "                \"question\": question,\n",
    "                \"answer\": answer,\n",
    "                \"source_doc\": sampled_context.metadata[\"source\"],\n",
    "            }\n",
    "        )\n",
    "    except:\n",
    "        continue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {
    "id": "aUlOUDv59jVN",
    "outputId": "c9634fdb-2a7f-43a6-c4eb-e60b166b8238"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>context</th>\n",
       "      <th>question</th>\n",
       "      <th>answer</th>\n",
       "      <th>source_doc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Now, we can just call the `Tokenizer.train` method with any list of files we want to use:\\n\\n&lt;tokenizerslangcontent&gt;\\n&lt;python&gt;\\n&lt;literalinclude&gt;\\n{\"path\": \"../../bindings/python/tests/documentation/test_quicktour.py\",\\n\"language\": \"python\",\\n\"start-after\": \"START train\",\\n\"end-before\": \"END train\",\\n\"dedent\": 8}\\n&lt;/literalinclude&gt;\\n&lt;/python&gt;\\n&lt;rust&gt;\\n&lt;literalinclude&gt;\\n{\"path\": \"../../tokenizers/tests/documentation.rs\",\\n\"language\": \"rust\",\\n\"start-after\": \"START quicktour_train\",\\n\"end-before\": \"END quicktour_train\",\\n\"dedent\": 4}\\n&lt;/literalinclude&gt;\\n&lt;/rust&gt;\\n&lt;node&gt;\\n&lt;literalinclude&gt;\\n{\"path\": \"../../bindings/node/examples/documentation/quicktour.test.ts\",\\n\"language\": \"js\",\\n\"start-after\": \"START train\",\\n\"end-before\": \"END train\",\\n\"dedent\": 8}\\n&lt;/literalinclude&gt;\\n&lt;/node&gt;\\n&lt;/tokenizerslangcontent&gt;\\n\\nThis should only take a few seconds to train our tokenizer on the full\\nwikitext dataset! To save the tokenizer in one file that contains all\\nits configuration and vocabulary, just use the\\n`Tokenizer.save` method:\\n\\n&lt;tokenizerslangcontent&gt;\\n&lt;python&gt;\\n&lt;literalinclude&gt;\\n{\"path\": \"../../bindings/python/tests/documentation/test_quicktour.py\",\\n\"language\": \"python\",\\n\"start-after\": \"START save\",\\n\"end-before\": \"END save\",\\n\"dedent\": 8}\\n&lt;/literalinclude&gt;\\n&lt;/python&gt;\\n&lt;rust&gt;\\n&lt;literalinclude&gt;\\n{\"path\": \"../../tokenizers/tests/documentation.rs\",\\n\"language\": \"rust\",\\n\"start-after\": \"START quicktour_save\",\\n\"end-before\": \"END quicktour_save\",\\n\"dedent\": 4}\\n&lt;/literalinclude&gt;\\n&lt;/rust&gt;\\n&lt;node&gt;\\n&lt;literalinclude&gt;\\n{\"path\": \"../../bindings/node/examples/documentation/quicktour.test.ts\",\\n\"language\": \"js\",\\n\"start-after\": \"START save\",\\n\"end-before\": \"END save\",\\n\"dedent\": 8}\\n&lt;/literalinclude&gt;\\n&lt;/node&gt;\\n&lt;/tokenizerslangcontent&gt;\\n\\nand you can reload your tokenizer from that file with the\\n`Tokenizer.from_file`\\n`classmethod`:</td>\n",
       "      <td>How can you reload a tokenizer from a file in Python?\\n</td>\n",
       "      <td>You can reload a tokenizer from a file in Python using the `Tokenizer.from_file` classmethod.</td>\n",
       "      <td>huggingface/tokenizers/blob/main/docs/source-doc-builder/quicktour.mdx</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                context  \\\n",
       "0  Now, we can just call the `Tokenizer.train` method with any list of files we want to use:\\n\\n<tokenizerslangcontent>\\n<python>\\n<literalinclude>\\n{\"path\": \"../../bindings/python/tests/documentation/test_quicktour.py\",\\n\"language\": \"python\",\\n\"start-after\": \"START train\",\\n\"end-before\": \"END train\",\\n\"dedent\": 8}\\n</literalinclude>\\n</python>\\n<rust>\\n<literalinclude>\\n{\"path\": \"../../tokenizers/tests/documentation.rs\",\\n\"language\": \"rust\",\\n\"start-after\": \"START quicktour_train\",\\n\"end-before\": \"END quicktour_train\",\\n\"dedent\": 4}\\n</literalinclude>\\n</rust>\\n<node>\\n<literalinclude>\\n{\"path\": \"../../bindings/node/examples/documentation/quicktour.test.ts\",\\n\"language\": \"js\",\\n\"start-after\": \"START train\",\\n\"end-before\": \"END train\",\\n\"dedent\": 8}\\n</literalinclude>\\n</node>\\n</tokenizerslangcontent>\\n\\nThis should only take a few seconds to train our tokenizer on the full\\nwikitext dataset! To save the tokenizer in one file that contains all\\nits configuration and vocabulary, just use the\\n`Tokenizer.save` method:\\n\\n<tokenizerslangcontent>\\n<python>\\n<literalinclude>\\n{\"path\": \"../../bindings/python/tests/documentation/test_quicktour.py\",\\n\"language\": \"python\",\\n\"start-after\": \"START save\",\\n\"end-before\": \"END save\",\\n\"dedent\": 8}\\n</literalinclude>\\n</python>\\n<rust>\\n<literalinclude>\\n{\"path\": \"../../tokenizers/tests/documentation.rs\",\\n\"language\": \"rust\",\\n\"start-after\": \"START quicktour_save\",\\n\"end-before\": \"END quicktour_save\",\\n\"dedent\": 4}\\n</literalinclude>\\n</rust>\\n<node>\\n<literalinclude>\\n{\"path\": \"../../bindings/node/examples/documentation/quicktour.test.ts\",\\n\"language\": \"js\",\\n\"start-after\": \"START save\",\\n\"end-before\": \"END save\",\\n\"dedent\": 8}\\n</literalinclude>\\n</node>\\n</tokenizerslangcontent>\\n\\nand you can reload your tokenizer from that file with the\\n`Tokenizer.from_file`\\n`classmethod`:   \n",
       "\n",
       "                                                  question  \\\n",
       "0  How can you reload a tokenizer from a file in Python?\\n   \n",
       "\n",
       "                                                                                          answer  \\\n",
       "0  You can reload a tokenizer from a file in Python using the `Tokenizer.from_file` classmethod.   \n",
       "\n",
       "                                                               source_doc  \n",
       "0  huggingface/tokenizers/blob/main/docs/source-doc-builder/quicktour.mdx  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(pd.DataFrame(outputs).head(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0KG4dNtg9jVN"
   },
   "source": [
    "### 1.3. Setup critique agents\n",
    "\n",
    "The questions generated by the previous agent can have many flaws: we should do a quality check before validating these questions.\n",
    "\n",
    "We thus build critique agents that will rate each question on several criteria, given in [this paper](https://huggingface.co/papers/2312.10003):\n",
    "- **Groundedness:** can the question be answered from the given context?\n",
    "- **Relevance:** is the question relevant to users? For instance, `\"What is the date when transformers 4.29.1 was released?\"` is not relevant for ML practitioners.\n",
    "\n",
    "One last failure case we've noticed is when a function is tailored for the particular setting where the question was generated, but undecipherable by itself, like `\"What is the name of the function used in this guide?\"`.\n",
    "We also build a critique agent for this criteria:\n",
    "- **Stand-alone**: is the question understandable free of any context, for someone with domain knowledge/Internet access? The opposite of this would be `What is the function used in this article?` for a question generated from a specific blog article.\n",
    "\n",
    "We systematically score functions with all these agents, and whenever the score is too low for any one of the agents, we eliminate the question from our eval dataset.\n",
    "\n",
    "💡 ___When asking the agents to output a score, we first ask them to produce its rationale. This will help us verify scores, but most importantly, asking it to first output rationale gives the model more tokens to think and elaborate an answer before summarizing it into a single score token.___\n",
    "\n",
    "We now build and run these critique agents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {
    "id": "05aSgTGs9jVO"
   },
   "outputs": [],
   "source": [
    "question_groundedness_critique_prompt = \"\"\"\n",
    "You will be given a context and a question.\n",
    "Your task is to provide a 'total rating' scoring how well one can answer the given question unambiguously with the given context.\n",
    "Give your answer on a scale of 1 to 5, where 1 means that the question is not answerable at all given the context, and 5 means that the question is clearly and unambiguously answerable with the context.\n",
    "\n",
    "Provide your answer as follows:\n",
    "\n",
    "Answer:::\n",
    "Evaluation: (your rationale for the rating, as a text)\n",
    "Total rating: (your rating, as a number between 1 and 5)\n",
    "\n",
    "You MUST provide values for 'Evaluation:' and 'Total rating:' in your answer.\n",
    "\n",
    "Now here are the question and context.\n",
    "\n",
    "Question: {question}\\n\n",
    "Context: {context}\\n\n",
    "Answer::: \"\"\"\n",
    "\n",
    "question_relevance_critique_prompt = \"\"\"\n",
    "You will be given a question.\n",
    "Your task is to provide a 'total rating' representing how useful this question can be to machine learning developers building NLP applications with the Hugging Face ecosystem.\n",
    "Give your answer on a scale of 1 to 5, where 1 means that the question is not useful at all, and 5 means that the question is extremely useful.\n",
    "\n",
    "Provide your answer as follows:\n",
    "\n",
    "Answer:::\n",
    "Evaluation: (your rationale for the rating, as a text)\n",
    "Total rating: (your rating, as a number between 1 and 5)\n",
    "\n",
    "You MUST provide values for 'Evaluation:' and 'Total rating:' in your answer.\n",
    "\n",
    "Now here is the question.\n",
    "\n",
    "Question: {question}\\n\n",
    "Answer::: \"\"\"\n",
    "\n",
    "question_standalone_critique_prompt = \"\"\"\n",
    "You will be given a question.\n",
    "Your task is to provide a 'total rating' representing how context-independent this question is.\n",
    "Give your answer on a scale of 1 to 5, where 1 means that the question depends on additional information to be understood, and 5 means that the question makes sense by itself.\n",
    "For instance, if the question refers to a particular setting, like 'in the context' or 'in the document', the rating must be 1.\n",
    "The questions can contain obscure technical nouns or acronyms like Gradio, Hub, Hugging Face or Space and still be a 5: it must simply be clear to an operator with access to documentation what the question is about.\n",
    "\n",
    "For instance, \"What is the name of the checkpoint from which the ViT model is imported?\" should receive a 1, since there is an implicit mention of a context, thus the question is not independent from the context.\n",
    "\n",
    "Provide your answer as follows:\n",
    "\n",
    "Answer:::\n",
    "Evaluation: (your rationale for the rating, as a text)\n",
    "Total rating: (your rating, as a number between 1 and 5)\n",
    "\n",
    "You MUST provide values for 'Evaluation:' and 'Total rating:' in your answer.\n",
    "\n",
    "Now here is the question.\n",
    "\n",
    "Question: {question}\\n\n",
    "Answer::: \"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "b9tbk7ME9jVO"
   },
   "outputs": [],
   "source": [
    "print(\"Generating critique for each QA couple...\")\n",
    "for output in tqdm(outputs):\n",
    "    evaluations = {\n",
    "        \"groundedness\": call_llm(\n",
    "            llm_client,\n",
    "            question_groundedness_critique_prompt.format(\n",
    "                context=output[\"context\"], question=output[\"question\"]\n",
    "            ),\n",
    "        ),\n",
    "        \"relevance\": call_llm(\n",
    "            llm_client,\n",
    "            question_relevance_critique_prompt.format(question=output[\"question\"]),\n",
    "        ),\n",
    "        \"standalone\": call_llm(\n",
    "            llm_client,\n",
    "            question_standalone_critique_prompt.format(question=output[\"question\"]),\n",
    "        ),\n",
    "    }\n",
    "    try:\n",
    "        for criterion, evaluation in evaluations.items():\n",
    "            score, eval = (\n",
    "                int(evaluation.split(\"Total rating: \")[-1].strip()),\n",
    "                evaluation.split(\"Total rating: \")[-2].split(\"Evaluation: \")[1],\n",
    "            )\n",
    "            output.update(\n",
    "                {\n",
    "                    f\"{criterion}_score\": score,\n",
    "                    f\"{criterion}_eval\": eval,\n",
    "                }\n",
    "            )\n",
    "    except Exception as e:\n",
    "        continue"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "IQv36Y_f9jVO"
   },
   "source": [
    "Now let us filter out bad questions based on our critique agent scores:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {
    "id": "oBWuOu1b9jVO",
    "outputId": "b32bacea-52f8-486a-96fe-5c188605c5a2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Evaluation dataset before filtering:\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>answer</th>\n",
       "      <th>groundedness_score</th>\n",
       "      <th>relevance_score</th>\n",
       "      <th>standalone_score</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>How can you reload a tokenizer from a file in Python?\\n</td>\n",
       "      <td>You can reload a tokenizer from a file in Python using the `Tokenizer.from_file` classmethod.</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>What is the output of my\\_cool\\_auth\\_method when passing both token and use\\_auth\\_token?\\n</td>\n",
       "      <td>UserWarning: Both `token` and `use_auth_token` are passed (...). `use_auth_token` value will be ignored. \"&lt;token&gt;\"</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Which version of Gradio introduced a hotfix to support pydantic v1 and v2?\\n</td>\n",
       "      <td>3.36.1</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Which model was released by Meta AI?\\n</td>\n",
       "      <td>DINOv2</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>What is the type of transformer that uses cross-attention?\\n</td>\n",
       "      <td>The type of transformer that uses cross-attention is the \"encoder-decoder\" transformer or the \"sequence-to-sequence\" transformer.</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>What is the license for the Llama-2-7b-Chat-64g-GPTQ model?\\n</td>\n",
       "      <td>The license for the Llama-2-7b-Chat-64g-GPTQ model is the llama-2-community-license.</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>What is the library for easily accessing and sharing datasets for Audio, Computer Vision, and Natural Language Processing tasks?\\n</td>\n",
       "      <td>🤗 Datasets</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Which feature improves performance for many applications?\\n</td>\n",
       "      <td>The feature that improves performance for many applications is lazy loading interactive or static variants of a component individually, rather than loading both variants regardless.</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                                                                                             question  \\\n",
       "0                                                                             How can you reload a tokenizer from a file in Python?\\n   \n",
       "1                                        What is the output of my\\_cool\\_auth\\_method when passing both token and use\\_auth\\_token?\\n   \n",
       "2                                                        Which version of Gradio introduced a hotfix to support pydantic v1 and v2?\\n   \n",
       "3                                                                                              Which model was released by Meta AI?\\n   \n",
       "4                                                                        What is the type of transformer that uses cross-attention?\\n   \n",
       "5                                                                       What is the license for the Llama-2-7b-Chat-64g-GPTQ model?\\n   \n",
       "6  What is the library for easily accessing and sharing datasets for Audio, Computer Vision, and Natural Language Processing tasks?\\n   \n",
       "7                                                                         Which feature improves performance for many applications?\\n   \n",
       "\n",
       "                                                                                                                                                                                  answer  \\\n",
       "0                                                                                          You can reload a tokenizer from a file in Python using the `Tokenizer.from_file` classmethod.   \n",
       "1                                                                     UserWarning: Both `token` and `use_auth_token` are passed (...). `use_auth_token` value will be ignored. \"<token>\"   \n",
       "2                                                                                                                                                                                 3.36.1   \n",
       "3                                                                                                                                                                                 DINOv2   \n",
       "4                                                      The type of transformer that uses cross-attention is the \"encoder-decoder\" transformer or the \"sequence-to-sequence\" transformer.   \n",
       "5                                                                                                   The license for the Llama-2-7b-Chat-64g-GPTQ model is the llama-2-community-license.   \n",
       "6                                                                                                                                                                             🤗 Datasets   \n",
       "7  The feature that improves performance for many applications is lazy loading interactive or static variants of a component individually, rather than loading both variants regardless.   \n",
       "\n",
       "   groundedness_score  relevance_score  standalone_score  \n",
       "0                 4.0              5.0               5.0  \n",
       "1                 1.0              1.0               5.0  \n",
       "2                 5.0              2.0               5.0  \n",
       "3                 5.0              5.0               5.0  \n",
       "4                 NaN              NaN               NaN  \n",
       "5                 4.0              4.0               5.0  \n",
       "6                 5.0              5.0               5.0  \n",
       "7                 4.0              4.0               5.0  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "============================================\n",
      "Final evaluation dataset:\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>answer</th>\n",
       "      <th>groundedness_score</th>\n",
       "      <th>relevance_score</th>\n",
       "      <th>standalone_score</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>How can you reload a tokenizer from a file in Python?\\n</td>\n",
       "      <td>You can reload a tokenizer from a file in Python using the `Tokenizer.from_file` classmethod.</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Which model was released by Meta AI?\\n</td>\n",
       "      <td>DINOv2</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>What is the license for the Llama-2-7b-Chat-64g-GPTQ model?\\n</td>\n",
       "      <td>The license for the Llama-2-7b-Chat-64g-GPTQ model is the llama-2-community-license.</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>What is the library for easily accessing and sharing datasets for Audio, Computer Vision, and Natural Language Processing tasks?\\n</td>\n",
       "      <td>🤗 Datasets</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Which feature improves performance for many applications?\\n</td>\n",
       "      <td>The feature that improves performance for many applications is lazy loading interactive or static variants of a component individually, rather than loading both variants regardless.</td>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                                                                                             question  \\\n",
       "0                                                                             How can you reload a tokenizer from a file in Python?\\n   \n",
       "3                                                                                              Which model was released by Meta AI?\\n   \n",
       "5                                                                       What is the license for the Llama-2-7b-Chat-64g-GPTQ model?\\n   \n",
       "6  What is the library for easily accessing and sharing datasets for Audio, Computer Vision, and Natural Language Processing tasks?\\n   \n",
       "7                                                                         Which feature improves performance for many applications?\\n   \n",
       "\n",
       "                                                                                                                                                                                  answer  \\\n",
       "0                                                                                          You can reload a tokenizer from a file in Python using the `Tokenizer.from_file` classmethod.   \n",
       "3                                                                                                                                                                                 DINOv2   \n",
       "5                                                                                                   The license for the Llama-2-7b-Chat-64g-GPTQ model is the llama-2-community-license.   \n",
       "6                                                                                                                                                                             🤗 Datasets   \n",
       "7  The feature that improves performance for many applications is lazy loading interactive or static variants of a component individually, rather than loading both variants regardless.   \n",
       "\n",
       "   groundedness_score  relevance_score  standalone_score  \n",
       "0                 4.0              5.0               5.0  \n",
       "3                 5.0              5.0               5.0  \n",
       "5                 4.0              4.0               5.0  \n",
       "6                 5.0              5.0               5.0  \n",
       "7                 4.0              4.0               5.0  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "pd.set_option(\"display.max_colwidth\", None)\n",
    "\n",
    "generated_questions = pd.DataFrame.from_dict(outputs)\n",
    "\n",
    "print(\"Evaluation dataset before filtering:\")\n",
    "display(\n",
    "    generated_questions[\n",
    "        [\n",
    "            \"question\",\n",
    "            \"answer\",\n",
    "            \"groundedness_score\",\n",
    "            \"relevance_score\",\n",
    "            \"standalone_score\",\n",
    "        ]\n",
    "    ]\n",
    ")\n",
    "generated_questions = generated_questions.loc[\n",
    "    (generated_questions[\"groundedness_score\"] >= 4)\n",
    "    & (generated_questions[\"relevance_score\"] >= 4)\n",
    "    & (generated_questions[\"standalone_score\"] >= 4)\n",
    "]\n",
    "print(\"============================================\")\n",
    "print(\"Final evaluation dataset:\")\n",
    "display(\n",
    "    generated_questions[\n",
    "        [\n",
    "            \"question\",\n",
    "            \"answer\",\n",
    "            \"groundedness_score\",\n",
    "            \"relevance_score\",\n",
    "            \"standalone_score\",\n",
    "        ]\n",
    "    ]\n",
    ")\n",
    "\n",
    "eval_dataset = datasets.Dataset.from_pandas(\n",
    "    generated_questions, split=\"train\", preserve_index=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "HaOMZyu69jVO"
   },
   "source": [
    "Now our synthetic evaluation dataset is complete! We can evaluate different RAG systems on this evaluation dataset.\n",
    "\n",
    "We have generated only a few QA couples here to reduce time and cost. But let's kickstart the next part by loading a pre-generated dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Q3RRz4W79jVO"
   },
   "outputs": [],
   "source": [
    "eval_dataset = datasets.load_dataset(\"m-ric/huggingface_doc_qa_eval\", split=\"train\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "K5s19uTd9jVO"
   },
   "source": [
    "# 2. Build our RAG System"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Z-mET8Dy9jVO"
   },
   "source": [
    "### 2.1. Preprocessing documents to build our vector database\n",
    "\n",
    "- In this part, __we split the documents from our knowledge base into smaller chunks__: these will be the snippets that are picked by the Retriever, to then be ingested by the Reader LLM as supporting elements for its answer.\n",
    "- The goal is to build semantically relevant snippets: not too small to be sufficient for supporting an answer, and not too large too avoid diluting individual ideas.\n",
    "\n",
    "Many options exist for text splitting:\n",
    "- split every `n` words / characters, but this has the risk of cutting in half paragraphs or even sentences\n",
    "- split after `n` words / character, but only on sentence boundaries\n",
    "- **recursive split** tries to preserve even more of the document structure, by processing it tree-like way, splitting first on the largest units (chapters) then recursively splitting on smaller units (paragraphs, sentences).\n",
    "\n",
    "To learn more about chunking, I recommend you read [this great notebook](https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/tutorials/LevelsOfTextSplitting/5_Levels_Of_Text_Splitting.ipynb) by Greg Kamradt.\n",
    "\n",
    "[This space](https://huggingface.co/spaces/m-ric/chunk_visualizer) lets you visualize how different splitting options affect the chunks you get.\n",
    "\n",
    "> In the following, we use Langchain's `RecursiveCharacterTextSplitter`.\n",
    "\n",
    "💡 _To measure chunk length in our Text Splitter, our length function will not be the count of characters, but the count of tokens in the tokenized text: indeed, for subsequent embedder that processes token, measuring length in tokens is more relevant and empirically performs better._"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "H4fhm55Q9jVO"
   },
   "outputs": [],
   "source": [
    "from langchain.docstore.document import Document as LangchainDocument\n",
    "\n",
    "RAW_KNOWLEDGE_BASE = [\n",
    "    LangchainDocument(page_content=doc[\"text\"], metadata={\"source\": doc[\"source\"]})\n",
    "    for doc in tqdm(ds)\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "sz9Jw2_q9jVO"
   },
   "outputs": [],
   "source": [
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from transformers import AutoTokenizer\n",
    "\n",
    "\n",
    "def split_documents(\n",
    "    chunk_size: int,\n",
    "    knowledge_base: List[LangchainDocument],\n",
    "    tokenizer_name: str,\n",
    ") -> List[LangchainDocument]:\n",
    "    \"\"\"\n",
    "    Split documents into chunks of size `chunk_size` characters and return a list of documents.\n",
    "    \"\"\"\n",
    "    text_splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(\n",
    "        AutoTokenizer.from_pretrained(tokenizer_name),\n",
    "        chunk_size=chunk_size,\n",
    "        chunk_overlap=int(chunk_size / 10),\n",
    "        add_start_index=True,\n",
    "        strip_whitespace=True,\n",
    "        separators=[\"\\n\\n\", \"\\n\", \".\", \" \", \"\"],\n",
    "    )\n",
    "\n",
    "    docs_processed = []\n",
    "    for doc in knowledge_base:\n",
    "        docs_processed += text_splitter.split_documents([doc])\n",
    "\n",
    "    # Remove duplicates\n",
    "    unique_texts = {}\n",
    "    docs_processed_unique = []\n",
    "    for doc in docs_processed:\n",
    "        if doc.page_content not in unique_texts:\n",
    "            unique_texts[doc.page_content] = True\n",
    "            docs_processed_unique.append(doc)\n",
    "\n",
    "    return docs_processed_unique"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QzBYfNG79jVO"
   },
   "source": [
    "### 2.2. Retriever - embeddings 🗂️\n",
    "The __retriever acts like an internal search engine__: given the user query, it returns the most relevant documents from your knowledge base.\n",
    "\n",
    "> For the knowledge base, we use Langchain vector databases since __it offers a convenient [FAISS](https://github.com/facebookresearch/faiss) index and allows us to keep document metadata throughout the processing__.\n",
    "\n",
    "🛠️ __Options included:__\n",
    "\n",
    "- Tune the chunking method:\n",
    "    - Size of the chunks\n",
    "    - Method: split on different separators, use [semantic chunking](https://python.langchain.com/docs/modules/data_connection/document_transformers/semantic-chunker)...\n",
    "- Change the embedding model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "LqJlIDZR9jVO"
   },
   "outputs": [],
   "source": [
    "from langchain.vectorstores import FAISS\n",
    "from langchain_community.embeddings import HuggingFaceEmbeddings\n",
    "from langchain_community.vectorstores.utils import DistanceStrategy\n",
    "import os\n",
    "\n",
    "\n",
    "def load_embeddings(\n",
    "    langchain_docs: List[LangchainDocument],\n",
    "    chunk_size: int,\n",
    "    embedding_model_name: Optional[str] = \"thenlper/gte-small\",\n",
    ") -> FAISS:\n",
    "    \"\"\"\n",
    "    Creates a FAISS index from the given embedding model and documents. Loads the index directly if it already exists.\n",
    "\n",
    "    Args:\n",
    "        langchain_docs: list of documents\n",
    "        chunk_size: size of the chunks to split the documents into\n",
    "        embedding_model_name: name of the embedding model to use\n",
    "\n",
    "    Returns:\n",
    "        FAISS index\n",
    "    \"\"\"\n",
    "    # load embedding_model\n",
    "    embedding_model = HuggingFaceEmbeddings(\n",
    "        model_name=embedding_model_name,\n",
    "        multi_process=True,\n",
    "        model_kwargs={\"device\": \"cuda\"},\n",
    "        encode_kwargs={\n",
    "            \"normalize_embeddings\": True\n",
    "        },  # set True to compute cosine similarity\n",
    "    )\n",
    "\n",
    "    # Check if embeddings already exist on disk\n",
    "    index_name = (\n",
    "        f\"index_chunk:{chunk_size}_embeddings:{embedding_model_name.replace('/', '~')}\"\n",
    "    )\n",
    "    index_folder_path = f\"./data/indexes/{index_name}/\"\n",
    "    if os.path.isdir(index_folder_path):\n",
    "        return FAISS.load_local(\n",
    "            index_folder_path,\n",
    "            embedding_model,\n",
    "            distance_strategy=DistanceStrategy.COSINE,\n",
    "        )\n",
    "\n",
    "    else:\n",
    "        print(\"Index not found, generating it...\")\n",
    "        docs_processed = split_documents(\n",
    "            chunk_size,\n",
    "            langchain_docs,\n",
    "            embedding_model_name,\n",
    "        )\n",
    "        knowledge_index = FAISS.from_documents(\n",
    "            docs_processed, embedding_model, distance_strategy=DistanceStrategy.COSINE\n",
    "        )\n",
    "        knowledge_index.save_local(index_folder_path)\n",
    "        return knowledge_index"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b6y1mQJX9jVO"
   },
   "source": [
    "### 2.3. Reader - LLM 💬\n",
    "\n",
    "In this part, the __LLM Reader reads the retrieved documents to formulate its answer.__\n",
    "\n",
    "🛠️ Here we tried the following options to improve results:\n",
    "- Switch reranking on/off\n",
    "- Change the reader model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9PdpuWyP9jVP"
   },
   "outputs": [],
   "source": [
    "RAG_PROMPT_TEMPLATE = \"\"\"\n",
    "<|system|>\n",
    "Using the information contained in the context,\n",
    "give a comprehensive answer to the question.\n",
    "Respond only to the question asked, response should be concise and relevant to the question.\n",
    "Provide the number of the source document when relevant.\n",
    "If the answer cannot be deduced from the context, do not give an answer.</s>\n",
    "<|user|>\n",
    "Context:\n",
    "{context}\n",
    "---\n",
    "Now here is the question you need to answer.\n",
    "\n",
    "Question: {question}\n",
    "</s>\n",
    "<|assistant|>\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9SDqenld9jVP"
   },
   "outputs": [],
   "source": [
    "from langchain_community.llms import HuggingFaceHub\n",
    "\n",
    "repo_id = \"HuggingFaceH4/zephyr-7b-beta\"\n",
    "READER_MODEL_NAME = \"zephyr-7b-beta\"\n",
    "HF_API_TOKEN = \"\"\n",
    "\n",
    "READER_LLM = HuggingFaceHub(\n",
    "    repo_id=repo_id,\n",
    "    task=\"text-generation\",\n",
    "    huggingfacehub_api_token=HF_API_TOKEN,\n",
    "    model_kwargs={\n",
    "        \"max_new_tokens\": 512,\n",
    "        \"top_k\": 30,\n",
    "        \"temperature\": 0.1,\n",
    "        \"repetition_penalty\": 1.03,\n",
    "    },\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "QZ62CbcZ9jVP"
   },
   "outputs": [],
   "source": [
    "from ragatouille import RAGPretrainedModel\n",
    "from langchain_core.vectorstores import VectorStore\n",
    "from langchain_core.language_models.llms import LLM\n",
    "\n",
    "\n",
    "def answer_with_rag(\n",
    "    question: str,\n",
    "    llm: LLM,\n",
    "    knowledge_index: VectorStore,\n",
    "    reranker: Optional[RAGPretrainedModel] = None,\n",
    "    num_retrieved_docs: int = 30,\n",
    "    num_docs_final: int = 7,\n",
    ") -> Tuple[str, List[LangchainDocument]]:\n",
    "    \"\"\"Answer a question using RAG with the given knowledge index.\"\"\"\n",
    "    # Gather documents with retriever\n",
    "    relevant_docs = knowledge_index.similarity_search(\n",
    "        query=question, k=num_retrieved_docs\n",
    "    )\n",
    "    relevant_docs = [doc.page_content for doc in relevant_docs]  # keep only the text\n",
    "\n",
    "    # Optionally rerank results\n",
    "    if reranker:\n",
    "        relevant_docs = reranker.rerank(question, relevant_docs, k=num_docs_final)\n",
    "        relevant_docs = [doc[\"content\"] for doc in relevant_docs]\n",
    "\n",
    "    relevant_docs = relevant_docs[:num_docs_final]\n",
    "\n",
    "    # Build the final prompt\n",
    "    context = \"\\nExtracted documents:\\n\"\n",
    "    context += \"\".join(\n",
    "        [f\"Document {str(i)}:::\\n\" + doc for i, doc in enumerate(relevant_docs)]\n",
    "    )\n",
    "\n",
    "    final_prompt = RAG_PROMPT_TEMPLATE.format(question=question, context=context)\n",
    "\n",
    "    # Redact an answer\n",
    "    answer = llm(final_prompt)\n",
    "\n",
    "    return answer, relevant_docs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hiygbqfT9jVP"
   },
   "source": [
    "# 3. Benchmarking the RAG system\n",
    "\n",
    "The RAG system and the evaluation datasets are now ready. The last step is to judge the RAG system's output on this evaluation dataset.\n",
    "\n",
    "To this end, __we setup a judge agent__. ⚖️🤖\n",
    "\n",
    "Out of [the different RAG evaluation metrics](https://docs.ragas.io/en/latest/concepts/metrics/index.html), we choose to focus only on faithfulness since it the best end-to-end metric of our system's performance.\n",
    "\n",
    "> We use GPT4 as a judge for its empirically good performance, but you could try with other models such as [kaist-ai/prometheus-13b-v1.0](https://huggingface.co/kaist-ai/prometheus-13b-v1.0) or [BAAI/JudgeLM-33B-v1.0](https://huggingface.co/BAAI/JudgeLM-33B-v1.0).\n",
    "\n",
    "💡 _In the evaluation prompt, we give a detailed description each metric on the scale 1-5, as is done in [Prometheus's prompt template](https://huggingface.co/kaist-ai/prometheus-13b-v1.0): this helps the model ground its metric precisely. If instead you give the judge LLM a vague scale to work with, the outputs will not be consistent enough between different examples._\n",
    "\n",
    "💡 _Again, prompting the LLM to output rationale before giving its final score gives it more tokens to help it formalize and elaborate a judgement._"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "VrlMh_ZI9jVP"
   },
   "outputs": [],
   "source": [
    "from langchain_core.language_models import BaseChatModel\n",
    "\n",
    "def run_rag_tests(\n",
    "    eval_dataset: datasets.Dataset,\n",
    "    llm,\n",
    "    knowledge_index: VectorStore,\n",
    "    output_file: str,\n",
    "    reranker: Optional[RAGPretrainedModel] = None,\n",
    "    verbose: Optional[bool] = True,\n",
    "    test_settings: Optional[str] = None,  # To document the test settings used\n",
    "):\n",
    "    \"\"\"Runs RAG tests on the given dataset and saves the results to the given output file.\"\"\"\n",
    "    try:  # load previous generations if they exist\n",
    "        with open(output_file, \"r\") as f:\n",
    "            outputs = json.load(f)\n",
    "    except:\n",
    "        outputs = []\n",
    "\n",
    "    for example in tqdm(eval_dataset):\n",
    "        question = example[\"question\"]\n",
    "        if question in [output[\"question\"] for output in outputs]:\n",
    "            continue\n",
    "\n",
    "        answer, relevant_docs = answer_with_rag(\n",
    "            question, llm, knowledge_index, reranker=reranker\n",
    "        )\n",
    "        if verbose:\n",
    "            print(\"=======================================================\")\n",
    "            print(f\"Question: {question}\")\n",
    "            print(f\"Answer: {answer}\")\n",
    "            print(f'True answer: {example[\"answer\"]}')\n",
    "        result = {\n",
    "            \"question\": question,\n",
    "            \"true_answer\": example[\"answer\"],\n",
    "            \"source_doc\": example[\"source_doc\"],\n",
    "            \"generated_answer\": answer,\n",
    "            \"retrieved_docs\": [doc for doc in relevant_docs],\n",
    "        }\n",
    "        if test_settings:\n",
    "            result[\"test_settings\"] = test_settings\n",
    "        outputs.append(result)\n",
    "\n",
    "        with open(output_file, \"w\") as f:\n",
    "            json.dump(outputs, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Ae-3KWzK9jVP"
   },
   "outputs": [],
   "source": [
    "EVALUATION_PROMPT = \"\"\"###Task Description:\n",
    "An instruction (might include an Input inside it), a response to evaluate, a reference answer that gets a score of 5, and a score rubric representing a evaluation criteria are given.\n",
    "1. Write a detailed feedback that assess the quality of the response strictly based on the given score rubric, not evaluating in general.\n",
    "2. After writing a feedback, write a score that is an integer between 1 and 5. You should refer to the score rubric.\n",
    "3. The output format should look as follows: \\\"Feedback: {{write a feedback for criteria}} [RESULT] {{an integer number between 1 and 5}}\\\"\n",
    "4. Please do not generate any other opening, closing, and explanations. Be sure to include [RESULT] in your output.\n",
    "\n",
    "###The instruction to evaluate:\n",
    "{instruction}\n",
    "\n",
    "###Response to evaluate:\n",
    "{response}\n",
    "\n",
    "###Reference Answer (Score 5):\n",
    "{reference_answer}\n",
    "\n",
    "###Score Rubrics:\n",
    "[Is the response correct, accurate, and factual based on the reference answer?]\n",
    "Score 1: The response is completely incorrect, inaccurate, and/or not factual.\n",
    "Score 2: The response is mostly incorrect, inaccurate, and/or not factual.\n",
    "Score 3: The response is somewhat correct, accurate, and/or factual.\n",
    "Score 4: The response is mostly correct, accurate, and factual.\n",
    "Score 5: The response is completely correct, accurate, and factual.\n",
    "\n",
    "###Feedback:\"\"\"\n",
    "\n",
    "from langchain.prompts.chat import (\n",
    "    ChatPromptTemplate,\n",
    "    HumanMessagePromptTemplate,\n",
    ")\n",
    "from langchain.schema import SystemMessage\n",
    "\n",
    "\n",
    "evaluation_prompt_template = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        SystemMessage(content=\"You are a fair evaluator language model.\"),\n",
    "        HumanMessagePromptTemplate.from_template(EVALUATION_PROMPT),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ia9Mvn859jVP"
   },
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "\n",
    "OPENAI_API_KEY = \"\"\n",
    "\n",
    "eval_chat_model = ChatOpenAI(model=\"gpt-4-1106-preview\", temperature=0, openai_api_key=OPENAI_API_KEY)\n",
    "evaluator_name = \"GPT4\"\n",
    "\n",
    "\n",
    "def evaluate_answers(\n",
    "    answer_path: str,\n",
    "    eval_chat_model,\n",
    "    evaluator_name: str,\n",
    "    evaluation_prompt_template: ChatPromptTemplate,\n",
    ") -> None:\n",
    "    \"\"\"Evaluates generated answers. Modifies the given answer file in place for better checkpointing.\"\"\"\n",
    "    answers = []\n",
    "    if os.path.isfile(answer_path):  # load previous generations if they exist\n",
    "        answers = json.load(open(answer_path, \"r\"))\n",
    "\n",
    "    for experiment in tqdm(answers):\n",
    "        if f\"eval_score_{evaluator_name}\" in experiment:\n",
    "            continue\n",
    "\n",
    "        eval_prompt = evaluation_prompt_template.format_messages(\n",
    "            instruction=experiment[\"question\"],\n",
    "            response=experiment[\"generated_answer\"],\n",
    "            reference_answer=experiment[\"true_answer\"],\n",
    "        )\n",
    "        eval_result = eval_chat_model.invoke(eval_prompt)\n",
    "        feedback, score = [\n",
    "            item.strip() for item in eval_result.content.split(\"[RESULT]\")\n",
    "        ]\n",
    "        experiment[f\"eval_score_{evaluator_name}\"] = score\n",
    "        experiment[f\"eval_feedback_{evaluator_name}\"] = feedback\n",
    "\n",
    "        with open(answer_path, \"w\") as f:\n",
    "            json.dump(answers, f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EXH-szLe9jVP"
   },
   "source": [
    "🚀 Let's run the tests and evaluate answers!👇"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "jW2nnvUT9jVQ"
   },
   "outputs": [],
   "source": [
    "if not os.path.exists(\"./output\"):\n",
    "    os.mkdir(\"./output\")\n",
    "\n",
    "for chunk_size in [200]:  # Add other chunk sizes (in tokens) as needed\n",
    "    for embeddings in [\"thenlper/gte-small\"]:  # Add other embeddings as needed\n",
    "        for rerank in [True, False]:\n",
    "            settings_name = f\"chunk:{chunk_size}_embeddings:{embeddings.replace('/', '~')}_rerank:{rerank}_reader-model:{READER_MODEL_NAME}\"\n",
    "            output_file_name = f\"./output/rag_{settings_name}.json\"\n",
    "\n",
    "            print(f\"Running evaluation for {settings_name}:\")\n",
    "\n",
    "            print(\"Loading knowledge base embeddings...\")\n",
    "            knowledge_index = load_embeddings(\n",
    "                RAW_KNOWLEDGE_BASE,\n",
    "                chunk_size=chunk_size,\n",
    "                embedding_model_name=embeddings,\n",
    "            )\n",
    "\n",
    "            print(\"Running RAG...\")\n",
    "            reranker = (\n",
    "                RAGPretrainedModel.from_pretrained(\"colbert-ir/colbertv2.0\")\n",
    "                if rerank\n",
    "                else None\n",
    "            )\n",
    "            run_rag_tests(\n",
    "                eval_dataset=eval_dataset,\n",
    "                llm=READER_LLM,\n",
    "                knowledge_index=knowledge_index,\n",
    "                output_file=output_file_name,\n",
    "                reranker=reranker,\n",
    "                verbose=False,\n",
    "                test_settings=settings_name,\n",
    "            )\n",
    "\n",
    "            print(\"Running evaluation...\")\n",
    "            evaluate_answers(\n",
    "                output_file_name,\n",
    "                eval_chat_model,\n",
    "                evaluator_name,\n",
    "                evaluation_prompt_template,\n",
    "            )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tytXV5-h9jVT"
   },
   "source": [
    "### Inspect results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "D4YDSfmr9jVT"
   },
   "outputs": [],
   "source": [
    "import glob\n",
    "\n",
    "outputs = []\n",
    "for file in glob.glob(\"./output/*.json\"):\n",
    "    output = pd.DataFrame(json.load(open(file, \"r\")))\n",
    "    output[\"settings\"] = file\n",
    "    outputs.append(output)\n",
    "result = pd.concat(outputs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "CdkXMNvS9jVT"
   },
   "outputs": [],
   "source": [
    "result[\"eval_score_GPT4\"] = result[\"eval_score_GPT4\"].apply(\n",
    "    lambda x: int(x) if isinstance(x, str) else 1\n",
    ")\n",
    "result[\"eval_score_GPT4\"] = (result[\"eval_score_GPT4\"] - 1) / 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "lgxBpid29jVT",
    "outputId": "9a3bcf32-4b0c-4df1-c76c-3ebbca82929d"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "settings\n",
       "./output/rag_chunk:200_embeddings:thenlper~gte-small_rerank:False_reader-model:zephyr-7b-beta.json       0.884328\n",
       "./output/rag_chunk:200_embeddings:BAAI~bge-base-en-v1.5_rerank:False_reader-model:zephyr-7b-beta.json    0.906716\n",
       "./output/rag_chunk:200_embeddings:BAAI~bge-base-en-v1.5_rerank:True_reader-model:zephyr-7b-beta.json     0.906716\n",
       "./output/rag_chunk:200_embeddings:thenlper~gte-small_rerank:True_reader-model:mixtral.json               0.906716\n",
       "./output/rag_chunk:200_embeddings:thenlper~gte-small_rerank:True_reader-model:zephyr-7b-beta.json        0.921642\n",
       "./output/rag_chunk:200_embeddings:thenlper~gte-small_rerank:True_reader-model:mixtral0.json              0.947761\n",
       "Name: eval_score_GPT4, dtype: float64"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "average_scores = result.groupby(\"settings\")[\"eval_score_GPT4\"].mean()\n",
    "average_scores.sort_values()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pSPH9DYI9jVT"
   },
   "source": [
    "## Example results\n",
    "\n",
    "Let us load the results that I obtained by tweaking the different options available in this notebook.\n",
    "For more detail on why these options could work or not, see the notebook on [advanced_RAG](advanced_rag).\n",
    "\n",
    "As you can see in the graph below, some tweaks do not bring any improvement, some give huge performance boosts.\n",
    "\n",
    "➡️ ___There is no single good recipe: you should try several different directions when tuning your RAG systems.___\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "RVOxatv99jVT"
   },
   "outputs": [],
   "source": [
    "import plotly.express as px\n",
    "\n",
    "scores = datasets.load_dataset(\"m-ric/rag_scores_cookbook\", split=\"train\")\n",
    "scores = pd.Series(scores[\"score\"], index=scores[\"settings\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "vqK0Dg2Q9jVT"
   },
   "outputs": [],
   "source": [
    "fig = px.bar(\n",
    "    scores,\n",
    "    color=scores,\n",
    "    labels={\n",
    "        \"value\": \"Accuracy\",\n",
    "        \"settings\": \"Configuration\",\n",
    "    },\n",
    "    color_continuous_scale=\"bluered\",\n",
    ")\n",
    "fig.update_layout(\n",
    "    width=1000,\n",
    "    height=600,\n",
    "    barmode=\"group\",\n",
    "    yaxis_range=[0, 100],\n",
    "    title=\"<b>Accuracy of different RAG configurations</b>\",\n",
    "    xaxis_title=\"RAG settings\",\n",
    "    font=dict(size=15),\n",
    ")\n",
    "fig.layout.yaxis.ticksuffix = \"%\"\n",
    "fig.update_coloraxes(showscale=False)\n",
    "fig.update_traces(texttemplate=\"%{y:.1f}\", textposition=\"outside\")\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dPUOMWGk9jVT"
   },
   "source": [
    "<img src=\"https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/RAG_settings_accuracy.png\" height=\"500\" width=\"800\">\n",
    "\n",
    "As you can see, these had varying impact on performance. In particular, tuning the chunk size is both easy and very impactful.\n",
    "\n",
    "But this is our case: your results could be very different: now that you have a robust evaluation pipeline, you can set on to explore other options! 🗺️"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "cookbook2",
   "language": "python",
   "name": "cookbook2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
